package cn.i7baozh.alibaba.sentinel.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 当接口被限流降级等措施阻断是会抛出BlockException
 * 这个异常无法被 @RestControllerAdvice 这种spring的全局异常处理器进行捕获或者处理
 * 只能使用以下这种方式，且只能有一个，不然启动的时候会报错。
 * @author zhangbaoqi532
 * @date 2024/12/30
 */
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String uri,
                       BlockException e) throws Exception {

        System.out.println(uri);
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setStatus(200);
        Map<String, String> data = new HashMap<>();
        data.put("code", "222");
        data.put("message", "发生了blockException");
        httpServletResponse.getWriter().println(JSON.toJSON(data));
    }
}
